import { ref } from 'vue'
import { useAuthStore } from '@/stores/auth'

export interface WSMessage {
  type: string
  data: any
}

export interface LogEvent {
  type: 'output_update' | 'execution_started' | 'execution_completed'
  executionId: string
  taskId: string
  newLine?: string
  fullOutput: string
  status: string
  duration?: number
  timestamp: string
}

class WebSocketService {
  private ws: WebSocket | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 3000
  private listeners: Map<string, Set<Function>> = new Map()
  private initialized = false
  
  public connected = ref(false)
  public connecting = ref(false)

  constructor() {
    // 不在构造函数中立即连接，而是延迟初始化
    console.log('[WebSocket] WebSocket服务已创建，等待初始化...')
  }

  public ensureInitialized() {
    if (!this.initialized) {
      console.log('[WebSocket] 首次初始化WebSocket连接...')
      this.initialized = true
      this.connect()
    }
  }

  private connect() {
    if (this.connecting.value || this.connected.value) {
      console.log('[WebSocket] 跳过连接，当前状态:', { connecting: this.connecting.value, connected: this.connected.value })
      return
    }

    console.log('[WebSocket] 开始建立连接...')
    this.connecting.value = true
    
    try {
      const authStore = useAuthStore()
      
      // 确定WebSocket URL
      let wsUrl: string
      if (import.meta.env.DEV) {
        // 开发环境：连接到后端服务器
        wsUrl = 'ws://localhost:3001/api/ws'
      } else {
        // 生产环境：使用当前域名
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        wsUrl = `${protocol}//${window.location.host}/api/ws`
      }
      
      console.log('[WebSocket] 连接URL:', wsUrl)
      console.log('[WebSocket] 认证token存在:', !!authStore.token)
      
      this.ws = new WebSocket(wsUrl)
      
      this.ws.onopen = () => {
        console.log('[WebSocket] 连接成功！')
        this.connected.value = true
        this.connecting.value = false
        this.reconnectAttempts = 0
        
        // 发送认证信息
        if (authStore.token) {
          console.log('[WebSocket] 发送认证信息')
          this.send('auth', { token: authStore.token })
        } else {
          console.warn('[WebSocket] 没有认证token')
        }
      }
      
      this.ws.onmessage = (event) => {
        try {
          const message: WSMessage = JSON.parse(event.data)
          console.log('[WebSocket] 收到原始消息:', event.data)
          console.log('[WebSocket] 解析后的消息:', message)
          this.handleMessage(message)
        } catch (error) {
          console.error('[WebSocket] 解析消息失败:', error, '原始数据:', event.data)
        }
      }
      
      this.ws.onclose = (event) => {
        console.log('[WebSocket] 连接关闭，代码:', event.code, '原因:', event.reason)
        this.connected.value = false
        this.connecting.value = false
        this.ws = null
        
        // 自动重连
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++
          console.log(`[WebSocket] ${this.reconnectInterval}ms后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
          setTimeout(() => this.connect(), this.reconnectInterval)
        } else {
          console.error('[WebSocket] 达到最大重连次数，停止重连')
        }
      }
      
      this.ws.onerror = (error) => {
        console.error('[WebSocket] 连接错误:', error)
        this.connecting.value = false
      }
      
    } catch (error) {
      console.error('[WebSocket] 创建连接失败:', error)
      this.connecting.value = false
    }
  }

  private handleMessage(message: WSMessage) {
    console.log('[WebSocket] 处理消息类型:', message.type, '数据:', message.data)
    
    const listeners = this.listeners.get(message.type)
    if (listeners) {
      console.log('[WebSocket] 找到监听器数量:', listeners.size)
      listeners.forEach(listener => {
        try {
          listener(message.data)
        } catch (error) {
          console.error('[WebSocket] 处理消息失败:', error)
        }
      })
    } else {
      console.warn('[WebSocket] 没有找到消息类型的监听器:', message.type)
    }
  }

  public send(type: string, data: any) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({ type, data }))
    } else {
      console.warn('[WebSocket] 连接未就绪，无法发送消息')
    }
  }

  public on(eventType: string, listener: Function) {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, new Set())
    }
    this.listeners.get(eventType)!.add(listener)
  }

  public off(eventType: string, listener: Function) {
    const listeners = this.listeners.get(eventType)
    if (listeners) {
      listeners.delete(listener)
    }
  }

  public disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.connected.value = false
    this.connecting.value = false
    this.reconnectAttempts = this.maxReconnectAttempts // 阻止自动重连
  }

  public reconnect() {
    this.disconnect()
    this.reconnectAttempts = 0
    this.connect()
  }
}

// 单例实例
export const wsService = new WebSocketService()

// 便捷方法
export function useWebSocket() {
  // 确保WebSocket服务已初始化
  wsService.ensureInitialized()
  
  return {
    connected: wsService.connected,
    connecting: wsService.connecting,
    on: wsService.on.bind(wsService),
    off: wsService.off.bind(wsService),
    send: wsService.send.bind(wsService),
    reconnect: wsService.reconnect.bind(wsService)
  }
} 